/**
 * Filename: NativeAlbumFragment.java
 * @author  Firefly
 * @contact postfirefly@163.com
 * @time    2016/3/10 1:11
 */
package com.github.postsanf.yinian.fragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.GridView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.postsanf.yinian.BaseApplication;
import com.github.postsanf.yinian.BaseFragment;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.activity.MainActivity;
import com.github.postsanf.yinian.activity.PublishActivity;
import com.github.postsanf.yinian.activity.pop.PopListAlbum;
import com.github.postsanf.yinian.activity.pop.PopListImageDir;
import com.github.postsanf.yinian.adapter.NativeStickyGridAdapter;
import com.github.postsanf.yinian.bean.YNAlbum;
import com.github.postsanf.yinian.bean.YNNativeImage;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.ISkinUpdate;
import com.github.postsanf.yinian.constants.SelectedImg;
import com.github.postsanf.yinian.constants.YNSingleton;
import com.github.postsanf.yinian.utils.DisplayUtils;
import com.github.postsanf.yinian.utils.ImageScanner;
import com.github.postsanf.yinian.utils.SkinPackageManager;
import com.github.postsanf.yinian.utils.TimeUtils;
import com.github.postsanf.yinian.utils.YNNativeComparator;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
/**
 * 本地图库
 */
public class NativeAlbumFragment extends BaseFragment implements View.OnClickListener, PopListAlbum.OnImageAlbumSelected,ISkinUpdate {
    private View                        view;                           // 上下文视图
    private ProgressDialog              mProgressDialog;
    private TextView                    btn_native_up_choose;
    private TextView                    btn_native_up_cancel;
    private ImageScanner                mScanner;
    private GridView                    mNative_grid_view;
    private Map<String, Integer>        sectionMap = new HashMap<>();
    private List<YNNativeImage>         mNativeImageList = new ArrayList<>();
    private static int                  section = 1;
    private boolean                     isChoose = false;
    private NativeStickyGridAdapter     mAdapter;
    private PopListAlbum                mPopListAlbumPopupWindow;		// 弹窗相册路径
    private int 						mScreenHeight;					// 屏高
    private RelativeLayout              rl_native_up_bottom;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        BaseApplication.getInstance().mActivitys.add(this);
        mScreenHeight 	 =  DisplayUtils.getScreenHeightPixels(getActivity());
        initListAlbumPopupWindw();
        initView();
        return view;
    }

    private void initView() {
        view = View.inflate(getActivity(), R.layout.yn_fragment_native_album, null);

        mNative_grid_view = (GridView) view.findViewById(R.id.native_grid_view);
        rl_native_up_bottom  = (RelativeLayout) view.findViewById(R.id.rl_native_up_bottom);
        btn_native_up_choose = (TextView) view.findViewById(R.id.btn_native_up_choose);
        btn_native_up_cancel =  (TextView) view.findViewById(R.id.btn_native_up_cancel);
        btn_native_up_choose.setOnClickListener(this);
        btn_native_up_cancel.setOnClickListener(this);
        mScanner = new ImageScanner(getActivity());
        mProgressDialog = ProgressDialog.show(getActivity(), null, "正在加载...");

        mScanner.scanImages(new ImageScanner.ScanCompleteCallBack() {
            @Override
            public void scanComplete(Cursor cursor) {
                // 关闭进度条
                mProgressDialog.dismiss();
                while (cursor.moveToNext()) {
                    // 获取图片的路径
                    String path = cursor.getString(cursor
                            .getColumnIndex(MediaStore.Images.Media.DATA));
                    long times = cursor.getLong(cursor
                            .getColumnIndex(MediaStore.Images.Media.DATE_ADDED));

                    YNNativeImage mNativeItem = new YNNativeImage(path, TimeUtils.paserTimeToYN(times));
                    mNativeImageList.add(mNativeItem);
                }
                cursor.close();
                Collections.sort(mNativeImageList, new YNNativeComparator());

                for (ListIterator<YNNativeImage> it = mNativeImageList.listIterator(); it.hasNext(); ) {
                    YNNativeImage mNativeItem = it.next();
                    String ym = mNativeItem.getTime();
                    if (!sectionMap.containsKey(ym)) {
                        mNativeItem.setSection(section);
                        sectionMap.put(ym, section);
                        section++;
                    } else {
                        mNativeItem.setSection(sectionMap.get(ym));
                    }
                }
                mAdapter = new NativeStickyGridAdapter(getActivity(), mNativeImageList, isChoose, NativeAlbumFragment.this);
                mNative_grid_view.setAdapter(mAdapter);
            }
        });
    }

    private String switchSure(int val)
    {
        return   val == 0 ?  "" : "("+val + ")";
    }

    public void setSureCount(int totals){
        btn_native_up_choose.setText("上传" + switchSure(totals));
    }



    @Override
    public void onClick(View v) {
        switch (v.getId()){
            // 选择发布
            case R.id.btn_native_up_choose:
                if (isChoose){
                   // 显示选择相册弹框
                    mPopListAlbumPopupWindow.showAtLocation(mNative_grid_view, Gravity.BOTTOM, 0, 0);
                    // 设置背景颜色变暗
                    WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
                    lp.alpha = .8f;
                    getActivity().getWindow().setAttributes(lp);
                }
                isChoose = true;
                mAdapter.setSelectStatus(isChoose);
                mAdapter.notifyDataSetChanged();
                btn_native_up_cancel.setVisibility(View.VISIBLE);
                break;
            // 取消发布
            case R.id.btn_native_up_cancel:
                SelectedImg.mSelectedImage.clear();
                isChoose = false;
                mAdapter.setSelectStatus(isChoose);
                mAdapter.notifyDataSetChanged();
                btn_native_up_choose.setText(getString(R.string.func_choose));
                btn_native_up_cancel.setVisibility(View.GONE);
        }
    }


    // 选择发布相册的弹框初始化
    private void initListAlbumPopupWindw()
    {
        mPopListAlbumPopupWindow = new PopListAlbum(
                ViewGroup.LayoutParams.MATCH_PARENT, (int) (mScreenHeight * 0.5),
                YNSingleton.getInstance().getAlbumList(), LayoutInflater.from(getActivity())
                .inflate(R.layout.yn_album_list_dir, null));
        mPopListAlbumPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss(){
                // 设置背景颜色
                WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
                lp.alpha = 1.0f;
                getActivity().getWindow().setAttributes(lp);
            }
        });
        mPopListAlbumPopupWindow.setOnImageAlbumSelected(this);
    }

    // 选择相册回调
    @Override
    public void selected(YNAlbum item){
        YNSingleton.getInstance().setCurAlbum(item);
        intent2Activity(PublishActivity.class);
        mPopListAlbumPopupWindow.dismiss();
        isChoose = false;
        mAdapter.setSelectStatus(isChoose);
        mAdapter.notifyDataSetChanged();
        btn_native_up_choose.setText(getString(R.string.func_choose));
        btn_native_up_cancel.setVisibility(View.GONE);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mProgressDialog.dismiss();
        BaseApplication.getInstance().mActivitys.remove(this);
    }

    @Override
    public void updateTheme(){
    try {
        Resources mResource= SkinPackageManager.getInstance(getActivity()).mResources;
        btn_native_up_choose.setTextColor(mResource.getColor(mResource.getIdentifier("border_color", CommonConstants.THEME_COLOR, CommonConstants.THEME_PACKAGE)));
        btn_native_up_cancel.setTextColor(mResource.getColor(mResource.getIdentifier("border_color", CommonConstants.THEME_COLOR, CommonConstants.THEME_PACKAGE)));
        rl_native_up_bottom.setBackgroundColor(mResource.getColor(mResource.getIdentifier("yncolor", CommonConstants.THEME_COLOR, CommonConstants.THEME_PACKAGE)));
        mAdapter.setResource(mResource);
    } catch (Exception e){
        e.printStackTrace();
    }
    }
    // 友盟统计
    public void onResume() {
        super.onResume();
        if(SkinPackageManager.getInstance(getActivity()).mResources!=null){
            updateTheme();
        }
        MobclickAgent.onPageStart("MainScreen");
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("MainScreen");
    }



}